package intro;

/**
 * 终止线程的良好操作
 * 利用中断 标志位
 * 
 * @author insight
 * @since 2021/8/23
 */
public class ShutDown {
    public static void main(String[] args) {
        Thread t1 = new Thread(new Runner(), "CountThread-1");

        // 使用中断终止
        t1.start();
        ThreadUtil.second(1);
        t1.interrupt();

        // 使用
        Runner runner = new Runner();
        Thread t2 = new Thread(runner, "CountThread-2");
        t2.start();
        ThreadUtil.second(1);
        runner.cancel();
    }

    static class Runner implements Runnable {
        private int i;
        private volatile boolean on = true;
        
        @Override
        public void run() {
            while (on && !Thread.currentThread().isInterrupted()) {
                ++i;
            }
            System.out.println("Count i = " + i);
        }
        
        public void cancel() {
            on = false;
        }
    }
}